package top.meeting.room.common.factory;

import com.jfinal.json.JFinalJson;

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Map;


/**
 * 我有故事，你有酒么？
 * JKhaled created by yunqisong@foxmail.com 2017/7/23
 * FOR : 重写Json转化类
 */
public class JKhaledJson extends JFinalJson {

    public static JKhaledJson getJson() {
        return new JKhaledJson();
    }

    protected String toJson(Object value, int depth) {
        if (value == null || (depth--) < 0)
             return "\"\"";

        if (value instanceof String)
            return "\"" + escape((String) value) + "\"";

        if (value instanceof Double) {
            if (((Double) value).isInfinite() || ((Double) value).isNaN())
                 return "\"\"";
            else
                return value.toString();
        }

        if (value instanceof Float) {
            if (((Float) value).isInfinite() || ((Float) value).isNaN())
                 return "\"\"";
            else
                return value.toString();
        }

        if (value instanceof Number)
            return value.toString();

        if (value instanceof Boolean)
            return value.toString();

        if (value instanceof java.util.Date) {
            String dp = "TimeStamp".equals(getDefaultDatePattern()) ? null : (datePattern != null ? datePattern : getDefaultDatePattern());
            if (value instanceof java.sql.Timestamp && dp != null) {
                    return "\"" + new SimpleDateFormat(timestampPattern).format(value) + "\"";
            }
            if (value instanceof java.sql.Time) {
                return "\"" + value.toString() + "\"";
            }
            // 优先使用对象级的属性 datePattern, 然后才是全局性的 defaultDatePattern
            if (dp != null) {
                return "\"" + new SimpleDateFormat(dp).format(value) + "\"";
            } else {
                return "\"" + ((java.util.Date) value).getTime() + "\"";
            }
        }

        if (value instanceof Collection) {
            return iteratorToJson(((Collection) value).iterator(), depth);
        }

        if (value instanceof Map) {
            return mapToJson((Map) value, depth);
        }

        String result = otherToJson(value, depth);
        if (result != null)
            return result;

        // 类型无法处理时当作字符串处理,否则ajax调用返回时js无法解析
        // return value.toString();
        return "\"" + escape(value.toString()) + "\"";
    }

}
